import { Component } from "react";
import { SearchOutlined } from "@ant-design/icons";
import {
  Row,
  Col,
  Modal,
  Input,
  Card,
  Checkbox,
  Tree,
  Button,
  message,
} from "antd";
import { findFirstBuildList } from "../../../ServeApi";
import { AjaxData } from "../../../../../../data/interface/publicInterface";
import { formattingTreeSelectTreeData } from "../../../../../../utils/common";
import TimeModePicker from "../../compontents/TimeModePicker";
import moment from "moment";
import "./index.less";

export interface BuildMessageProps {
  onSubmit: (data: EnergyReportData) => any;
}

export interface BuildMessageState {
  idList: string[];
}
export interface EnergyReportData {
  idList: string[];
  time: number;
  timeType: number;
  name: string;
}
class BuildMessage extends Component<BuildMessageProps, BuildMessageState> {
  public checkedKeys: string[] = [];
  private treeSelectData: any[] = [];
  private isCascade: boolean = false; //是否级联
  private isSelectAll: boolean = false; //是否全选
  private selectAllArr: string[] = []; //全选所需的id
  private ipv: string = "";
  private buildName = "";
  state = {
    idList: [],
  };
  public dataJson: any = {};
  render() {
    return (
      <>
        <Card title="建筑信息" className="BuildMessage" id="BuildMessage">
          <div className="box">
            <Row>
              <Col span={24}>
                <TimeModePicker
                  onChange={(date: string, dateString: string) => {
                    this.getDate(date, dateString);
                  }}
                />
              </Col>
              <Col span={24}>
                <Checkbox
                  checked={this.isSelectAll}
                  onChange={(e) => {
                    this.isSelectAll = e.target.checked;
                    if (e.target.checked) {
                      this.checkedKeys = this.selectAllArr;
                    } else {
                      this.checkedKeys = [];
                    }
                    this.setState({ idList: this.checkedKeys });
                    this.buildName = "爱尔眼科";
                    this.forceUpdate();
                  }}
                >
                  全选
                </Checkbox>
                {/* <Checkbox
                  checked={this.isCascade}
                  onChange={(e) => {
                    this.isCascade = e.target.checked;
                    this.checkedKeys = []; //清空
                    this.isSelectAll = false;
                    this.setState({ idList: this.checkedKeys });
                    this.forceUpdate();
                  }}
                >
                  是否级联
                </Checkbox> */}
              </Col>
              <Col span={24}>
                <Input
                  placeholder="请输入关键字过滤"
                  value={this.ipv}
                  onChange={(e) => {
                    this.ipv = e.target.value;
                    this.forceUpdate();
                  }}
                  suffix={
                    <SearchOutlined
                      onClick={() => {
                        this.getSelectList(this.ipv);
                      }}
                    />
                  }
                />
              </Col>
            </Row>
            {this.treeSelectData.length > 0 ? (
              <Tree
                // checkable
                defaultExpandAll
                checkedKeys={this.checkedKeys}
                // onCheck={this.onCheck}
                treeData={this.treeSelectData}
                checkStrictly={!this.isCascade}
                style={{ paddingBottom: 24 }}
                onSelect={(selectedKeys, info) => {
                  this.onSelect(selectedKeys, info);
                }}
              />
            ) : null}
          </div>
          <Button
            type="primary"
            className="shengcheng"
            block
            style={{ position: "absolute", bottom: 0, left: 0 }}
            onClick={() => {
              this.onsubmit();
            }}
          >
            生成
          </Button>
        </Card>
      </>
    );
  }
  componentDidMount() {
    let oPre: any = document.getElementById("fdsgafsdhfdhsgfh");
    let oCard: any = document.getElementById("BuildMessage");
    let oMain: any = document.getElementById("main");
    let wi: string = oPre.offsetWidth - 12 + "px";
    oCard.style.width = wi;

    oMain.addEventListener("scroll", (e) => {
      if (oMain?.scrollTop > 53) {
        oCard.style.position = "fixed";
        oCard.style.top = "60px";
      } else {
        oCard.style.position = "static";
      }
    });
  }

  getDate(date: string, dateString: string) {
    let num: number = 2;
    switch (date) {
      case "date":
        num = 2;
        break;
      case "month":
        num = 3;
        break;
      case "year":
        num = 4;
        break;
      default:
        break;
    }
    this.dataJson.timeType = num;
    this.dataJson.time = moment(dateString).valueOf();
  }
  /**主动触发 */
  //生成
  onsubmit() {
    let { idList } = this.state;
    let len = idList.length;
    let pream: EnergyReportData = {
      idList,
      time: this.dataJson.time,
      timeType: this.dataJson.timeType,
      name: this.buildName,
    };
    if (len > 0) {
      this.props.onSubmit(pream);
    } else {
      message.error("请至少选择一个建筑");
    }
  }
  //树点击
  onSelect = (selectedKeys, info) => {
    this.checkedKeys = selectedKeys;
    this.isSelectAll = false;
    this.setState({
      idList: this.checkedKeys,
    });
    console.log(info.node.title);
    this.buildName = info.node.title;
    this.forceUpdate();
  };

  componentWillMount() {
    this.getSelectList();
  }
  /**方法函数调用 */
  //格式化树状选择数据
  getTreeData(arr: any[]) {
    let selectAllArr: string[] = [];
    let array = arr.map((item) => {
      selectAllArr.push("" + item.id);
      return {
        key: "" + item.id,
        id: item.id,
        pId: item.parentId,
        value: "" + item.id,
        title: item.name,
      };
    });
    this.selectAllArr = selectAllArr;
    this.treeSelectData = formattingTreeSelectTreeData(array);

    this.forceUpdate();
  }
  /**请求数据 */
  //获取建筑选择项
  async getSelectList(str?: string) {
    let _this = this;
    let pream = {
      name: str ? str : "",
    };
    try {
      ///files/build/findFirstBuildList
      let res: any = await findFirstBuildList(
        JSON.stringify(pream)
      ).catch((err) => {});
      let json: AjaxData = res;
      if (json.success) {
        _this.getTreeData(json.data);
        _this.checkedKeys = [];
        _this.setState({ idList: _this.checkedKeys });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {},
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {},
      });
      console.error(error);
    }
  }
}

export default BuildMessage;
